import store from "../store";
import { checkLogin } from "./login";
import { getUserPhoneNumber, login } from "../api/public";
import Cache from "../utils/cache";
import { saveLoginEndTime } from "@/utils/auth.js";
import { STATE_R_KEY, USER_INFO } from "./../config/cache";
import util from "@/utils/util";
import { H5_APP_ID, H5_BASE_URL, LOCAL_URL } from "@/config/app";

import { bindDistributionUserApi } from "@/api/user";

class Routine {
  constructor() {
    this.scopeUserInfo = "scope.userInfo";
    this.objStatus = {
      weixin: 0,
      toutiao: 1,
    };
  }
  async getUserCode() {
    let isAuth = await this.isAuth(),
      code = "";
    if (isAuth) code = await this.getCode();
    return code;
  }

  /**
   * 获取用户信息
   */
  getUserProfile() {
    let that = this,
      code = this.getUserCode();

    return new Promise((resolve, reject) => {
      uni.getUserProfile({
        lang: "zh_CN",
        desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success(user) {
          if (code) user.code = code;
          resolve({
            userInfo: user,
            islogin: false,
          });
        },
        fail(res) {
          reject(res);
        },
      });
    });
  }
  /**
   * 获取用户信息
   */
  authorize() {
    let that = this;
    return new Promise((resolve, reject) => {
      if (checkLogin())
        return resolve({
          userInfo: Cache.get(USER_INFO, true),
          islogin: true,
        });
      uni.authorize({
        scope: that.scopeUserInfo,
        success() {
          resolve({
            islogin: false,
          });
        },
        fail(res) {
          reject(res);
        },
      });
    });
  }
  async getCode() {
    let provider = await this.getProvider();
    return new Promise((resolve, reject) => {
      uni.login({
        provider: provider,
        success(res) {
          // #ifdef MP-TOUTIAO
          let detail = res.errMsg.split(":")[1];
          if (detail !== "ok") {
            util.Tips("已取消授权");
          } else {
            if (res.code) Cache.set(STATE_R_KEY, res.code, 10800);
            return resolve(res.code);
          }
          // #endif
          // #ifdef MP-WEIXIN
          if (res.code) Cache.set(STATE_R_KEY, res.code, 10800);
          return resolve(res.code);
          // #endif
        },
        fail() {
          return reject(null);
        },
      });
    });
  }

  /**
   * 获取服务供应商
   */
  getProvider() {
    return new Promise((resolve, reject) => {
      uni.getProvider({
        service: "oauth",
        success(res) {
          resolve(res.provider);
        },
        fail() {
          resolve(false);
        },
      });
    });
  }
  /**
   * 是否授权
   */
  isAuth() {
    let that = this;
    return new Promise((resolve, reject) => {
      uni.getSetting({
        success(res) {
          if (!res.authSetting[that.scopeUserInfo]) {
            resolve(true);
          } else {
            resolve(true);
          }
        },
        fail() {
          resolve(false);
        },
      });
    });
  }
  /**
   * 小程序登录
   */
  async authUserInfo(code, data) {
    let provider = await this.getProvider();
    let type = this.objStatus[provider[0]];
    let par = Cache.get("params") && JSON.parse(Cache.get("params"));
    // let scene = Cache.get('scene') && JSON.parse(Cache.get('scene'))
    // console.log(scene);
    store.commit("SET_LOGINTYPE", type);
    return new Promise((resolve, reject) => {
      login({ code: code, phoneCode: data.code, ...par })
        .then(async (res) => {
          if (res.code === 200) {
            if (res.data.type == "login") {
              store.commit("LOGIN", {
                token: res.data.tokenHead + res.data.token,
              });
              saveLoginEndTime(res.data.expiresIn);
              store.commit("SETUID", res.data.memberId);
              await store.dispatch("USERINFO");
              await this.bindSpUid();
              return resolve(res);
            }
            if (res.data.type == "register") {
              getUserPhoneNumber({ key: res.data.key }).then(async (phone) => {
                if (phone.code === 200) {
                  store.commit("LOGIN", {
                    token: phone.data.tokenHead + phone.data.token,
                  });
                  store.commit("SETUID", phone.data.memberId);
                  saveLoginEndTime(phone.data.expiresIn);
                  await store.dispatch("USERINFO", phone.data.memberId);

                  return resolve(phone);
                } else {
                  return util.Tips("当前账户未激活，请联系管理员！");
                }
              });
            } else {
              util.Tips("当前账户未激活，请联系管理员！");
            }
          }
          // 如果用户账号未在PC端注册
          if (res.code === 500) {
            // this.$util.Tips(res.message)
            return reject(res);
          }
        })
        .catch((res) => {
          return reject(res);
        });
    });
  }

  bindSpUid() {
    let params = Cache.get("params") && JSON.parse(Cache.get("params"));
    const userInfo = Cache.get(USER_INFO)
    let userId 
    if(userInfo) {
      try {
        userId = JSON.parse(userInfo)?.id
      } catch {
        console.log('解析userId失败')
      }
    } 
    if (params?.activityUserId && userId !== params.id) {
      let data = {
        bindUserId: params.activityUserId,
      };
      console.log("data", data);
      bindDistributionUserApi(data).then((res) => {
        console.log("res", res);
      });
    }
  }

  // #ifdef H5 || mp
  // 是否为微信公众号
  isWeixin() {
    return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  }
  // 公众号登录
  authLogin() {
    if (this.getCode1()?.code) {
      return this.getCode1().code;
    } else {
      location.href = `${H5_BASE_URL}?appid=${H5_APP_ID}&redirect_uri=${LOCAL_URL}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
      return false;
    }
  }

  //公众号登录
  wechaLogin() {}

  // 公众号获取地址栏返回的code
  getCode1() {
    if (!store.state.app.isLogin) {
      const code = location.href.split("?")[1];
      if (!code) return {};
      const obj = {};
      code.split("&").forEach((item) => {
        const arr = item.split("=");
        obj[arr[0]] = arr[1];
      });
      return obj;
    }
  }
  // #endif

  //获取经纬度

  gettLocation() {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      uni.getLocation({
        type: "gcj02",
        altitude: true,
        isHighAccuracy: true,
        success: function (res) {
          resolve(res);
        },
        fail(error) {
          reject(error);
          console.log("失败", error);
        },
      });
      // #endif

      // #ifdef MP-WEIXIN
      uni.getSetting({
        success(res) {
          if (!res.authSetting["scope.userLocation"]) {
            wx.authorize({
              scope: "scope.userLocation",
              success: function () {
                uni.getLocation({
                  type: "gcj02",
                  altitude: true,
                  isHighAccuracy: true,
                  success: function (res) {
                    resolve(res);
                  },
                  fail: function (res) {
                    reject(res);
                  },
                });
              },
              fail(error) {
                uni.showModal({
                  title: "提示",
                  content: "若点击不授权，将无法使用位置功能",
                  cancelText: "不授权",
                  success(res) {
                    if (res.confirm) {
                      uni.openSetting({
                        success(res) {
                          console.log(res);
                          wx.getLocation({
                            type: "gcj02",
                            altitude: true,
                            isHighAccuracy: true,
                            success: function (res) {
                              resolve(res);
                            },
                            fail(error) {
                              reject(error);
                              console.log("失败", error);
                            },
                          });
                        },
                        fail(error) {
                          console.log("error", error);
                          uni.$emit("getLocation", "no");
                        },
                      });
                    } else if (res.cancel) {
                      uni.$emit("getLocation", "no");
                    }
                  },
                });
              },
            });
          } else {
            wx.getLocation({
              type: "gcj02",
              altitude: true,
              isHighAccuracy: true,
              success: function (res) {
                resolve(res);
              },
              fail(error) {
                reject(error);
                console.log("失败", error);
              },
            });
          }
        },
      });
      // #endif
    });
  }
}

export default new Routine();
